package com.linxcong.security.server.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * @Author:linchong
 * @CreateTime:2020-07-14 12:23
 * @Description: 配置passwordEncoder和authenticationManager
 */
@Configuration
@EnableWebSecurity
public class OAuth2WebSecurityConfig extends WebSecurityConfigurerAdapter {

	/*
	 * 扩展信息：
	 * AuthenticationManager接口只有一个方法： authenticate
	 * Authentication authenticate(Authentication authentication)
	 * 			throws AuthenticationException;
	 *
	 * 方法封装了认证的信息，Authentication
	 */


	/**
	 * 查询用户，密码比对是在authenticationManager
	 */
	@Autowired
	private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private LogoutSuccessHandler oAuth2LogoutSuccessHandler;

	/**
	 * 构建authenticationManager，需要userDetailsService,passwordEncoder,配置authenticationManager
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService)
				.passwordEncoder(passwordEncoder);
	}

	/**
	 * 暴露authenticationManager给spring管理
	 * @return
	 * @throws Exception
	 */
	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		/*super.configure(http);
		http.logout().logoutSuccessUrl("http://admin.chong.com:8080/index");*/
		http.authorizeRequests()
				.anyRequest().authenticated()
				.and()
				.formLogin().and()
				.logout().logoutSuccessHandler(oAuth2LogoutSuccessHandler);

	}
}
